package com.common.server.modules.dict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.common.server.common.util.Tree;
import com.common.server.modules.dict.entity.Dict;
import com.common.server.modules.dict.mapper.DictMapper;
import com.common.server.modules.dict.service.DictService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author ostrich
 * @since 2019-10-09
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;

    @Override
    public List<Tree<Dict>> getDictTree(Dict dict) {
        //1查询出所有字典
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>(dict);
        queryWrapper.orderByAsc("order_index");
        List<Dict> originalData = dictMapper.selectList(queryWrapper);
        //2过滤出所有顶级字典
        List<Dict> rootData = originalData.parallelStream().
                filter(obj -> (obj != null && Objects.equals(obj.getParentId(), "0"))).collect(Collectors.toList());

        CopyOnWriteArrayList<Tree<Dict>> list = new CopyOnWriteArrayList<>();
        // 为一级数据设置子级，getChild是递归调用的
        rootData.parallelStream().forEachOrdered(parentObj -> {
            if (Objects.equals(parentObj.getParentId(), "0")) {
                Tree<Dict> parentTree = new Tree<>();
                parentTree.setLabel(parentObj.getValue());
                parentTree.setId(parentObj.getId());
                Map<String, Object> attribute = Maps.newHashMap();
                attribute.put("code", parentObj.getCode());
                attribute.put("orderIndex",parentObj.getOrderIndex());
                parentTree.setAttributes(attribute);
                parentTree.setChildren(getChild(parentObj.getId(), originalData));
                parentTree.setParentId(parentObj.getParentId());
                list.add(parentTree);
            }
        });

        return list;
    }

    @Override
    public List<Map<String, Object>> getKVList(String type) {
        return dictMapper.getKVList(type);
    }

    /**
     * 递归获取子级
     *
     * @param pId          父id
     * @param originalData 所有菜单(权限)
     * @return
     */
    private static List<Tree<Dict>> getChild(String pId, List<Dict> originalData) {

        // 子菜单
        Set<Tree<Dict>> childList = new CopyOnWriteArraySet<>();
        //转换子级
        originalData.parallelStream().forEachOrdered(childObj -> {
            // 遍历所有节点，将父id与传过来的id比较
            if (!Objects.equals(childObj.getParentId(), "0")
                    && Objects.equals(pId, childObj.getParentId())) {
                Tree<Dict> childTree = new Tree<>();
                childTree.setLabel(childObj.getValue());
                childTree.setId(childObj.getId());
                childTree.setParentId(childObj.getParentId());
                childTree.setHasParent(true);
                Map<String, Object> attribute = Maps.newHashMap();
                attribute.put("code", childObj.getCode());
                attribute.put("orderIndex", childObj.getOrderIndex());
                childTree.setAttributes(attribute);
                childList.add(childTree);
            }
        });

        // 把子菜单的子菜单再循环一遍
        childList.parallelStream().forEach(child -> {
            //递归
            child.setChildren(getChild(child.getId(), originalData));
        });
        return childList.size() > 0 ? Lists.newArrayList(childList) : null;
    }
}
